package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

/**
 * @author kcs
 * @date 2021/11/17
 * @TIME:13:16
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request,@RequestBody Employee employee){

        //1.将页面提交的密码进行md5加密
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //2.根据页面提交的用户名查询数据库
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getUsername,employee.getUsername());
        Employee emp = employeeService.getOne(lqw);

        //3.如果没有查询到则返回登录失败
        if(emp == null){
            return R.error("该用户不存在");
        }

        //4.密码比对,如果不一致返回登录失败结果
        if(!emp.getPassword().equals(password)){
            return R.error("密码错误");
        }

        //5.查看员工状态,如果为已禁用状态,则返回员工已禁用结果
        if(emp.getStatus() == 0){
            return R.error("此账号已禁用");
        }

        //6.登录成功,将员工id存入Session并返回登录成功结果
        request.getSession().setAttribute("employee",emp.getId());
        return R.success(emp);
    }

    /**
     * 员工退出
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){

        //清理Session中保存的当前登录用户id,返回结果
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    /**
     * 新增员工
     * @param employee
     * @param request
     * @return
     */
    @PostMapping
    public R add(@RequestBody Employee employee,HttpServletRequest request){

        /*//判断员工是否已存在 -- 用异常处理器进行处理 SQLIntegrityConstraintViolationException 违反sql完整性约束
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getUsername,employee.getUsername());
        Employee one = employeeService.getOne(wrapper);
        //若存在,直接返回结果
        if(one != null){
            return R.error("添加失败,用户已存在");
        }*/

        //补全员工信息
        //HttpSession session = request.getSession();
        //Long userId = (Long) session.getAttribute("employee");
        //employee.setCreateTime(LocalDateTime.now());
        //employee.setUpdateTime(LocalDateTime.now());
        //employee.setCreateUser(userId);
        //employee.setUpdateUser(userId);
        String password = DigestUtils.md5DigestAsHex("123456".getBytes());
        employee.setPassword(password);

        //添加并返回结果
        employeeService.save(employee);
        return R.success("添加成功");
    }

    /**
     * 员工分页条件查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R getByPage(Integer page, Integer pageSize, String name){

        //1.设置分页查询条件
        IPage<Employee> iPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name != null,Employee::getName,name);
        employeeService.page(iPage,wrapper);

        //2.如果查询页码大于总页数时,设置当前页码为总页数
        if(iPage.getCurrent() > iPage.getPages()){
            iPage.setCurrent(iPage.getPages());
            employeeService.page(iPage,wrapper);
        }
        return R.success(iPage);
    }

    /**
     * 启用禁用员工账号 + 编辑员工信息
     * @param employee
     * @return
     */
    @PutMapping
    public R update(@RequestBody Employee employee,HttpServletRequest request){

        //管理员账号不允许被修改
        if(employee.getId() == 1){
            return R.error("该账号不允许被修改");
        }

        //判断用户是否存在 -- 防止多人同时操作(可加乐观锁解决)
        Employee one = employeeService.getById(employee.getId());
        if(one == null){
            return R.error("用户不存在");
        }

        //设置更新信息
        //employee.setStatus(employee.getStatus());
        //employee.setUpdateTime(LocalDateTime.now());
        HttpSession session = request.getSession();
        Long empId = (Long) session.getAttribute("employee");
        //employee.setUpdateUser(empId);

        if(employee.getId().longValue() == empId.longValue() || empId == 1L){
            //修改
            employeeService.updateById(employee);
            return R.success("修改成功");
        }else {
            return R.error("权限不足");
        }
    }

    /**
     * 编辑员工信息 -- 回显
     * @param userId
     * @return
     */
    @GetMapping("/{userId}")
    public R getByID(@PathVariable Long userId){

        if(userId == null){
            return R.error("参数非法");
        }

        Employee one = employeeService.getById(userId);
        return R.success(one);
    }

}
